package org.assistant.common.jdbc.datasource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DriverManagerDataSource extends AbstractDriverBasedDataSource {
	protected final static Log log = LogFactory
		.getLog(DriverManagerDataSource.class);
	protected final static boolean isDebugEnabled = log.isDebugEnabled();

	public DriverManagerDataSource() {
	}

	public DriverManagerDataSource(String url) {
		setUrl(url);
	}

	public DriverManagerDataSource(String url, String username, String password) {
		setUrl(url);
		setUsername(username);
		setPassword(password);
	}

	public DriverManagerDataSource(String url, Properties conProps) {
		setUrl(url);
		setConnectionProperties(conProps);
	}

	public DriverManagerDataSource(String driverClassName, String url,
			String username, String password) {
		setDriverClassName(driverClassName);
		setUrl(url);
		setUsername(username);
		setPassword(password);
	}

	public Connection getConnection() throws SQLException {
		return getConnectionFromDriver(getUsername(), getPassword());
	}

	public Connection getConnection(String username, String password)
			throws SQLException {
		return getConnectionFromDriver(username, password);
	}

	/**
	 * 从数据库驱动中获取连接
	 * 
	 * @param username
	 * @param password
	 * @return
	 * @throws SQLException
	 */
	private Connection getConnectionFromDriver(String username, String password)
			throws SQLException {
		Properties props = new Properties(getConnectionProperties());
		if (username != null) {
			props.setProperty("user", username);
		}
		if (password != null) {
			props.setProperty("password", password);
		}

		String url = getUrl();
		if (isDebugEnabled) {
			log.debug("Creating new JDBC DriverManager Connection to [" + url
					+ "]");
		}
		return DriverManager.getConnection(url, props);
	}
}
